package com.xyzwps.collections.map;

import com.xyzwps.collections.List;
import com.xyzwps.collections.list.ArrayList;

/**
 * 这是一个超级简单的 {@link Map} 实现。
 */
public class DemoMap<K, V> implements Map<K, V> {

    private final List<K> keys = new ArrayList<>();
    private final List<V> values = new ArrayList<>();

    @Override
    public void put(K key, V value) {
        final int indexOfKey = keys.indexOf(key);
        if (indexOfKey < 0) {
            keys.add(key);
            values.add(value);
        } else {
            values.putAt(indexOfKey, value);
        }
    }

    @Override
    public V get(K key) {
        final int indexOfKey = keys.indexOf(key);
        return indexOfKey < 0 ? null : values.getAt(indexOfKey);
    }

    @Override
    public boolean remove(K key) {
        final int indexOfKey = keys.indexOf(key);
        if (indexOfKey < 0) {
            return false;
        } else {
            keys.removeAt(indexOfKey);
            values.removeAt(indexOfKey);
            return true;
        }
    }

    @Override
    public boolean hasKey(K key) {
        return keys.has(key);
    }

    @Override
    public int size() {
        return this.keys.size();
    }
}
